<template>
  <div class="login-container">
    <div class="login-header" style="-webkit-app-region: drag">
      <div class="title">IM登录</div>
      <a @click="close" class="close" href="javascript:void(0)" style="-webkit-app-region: no-drag">
        <svg-icon icon-class="close"/>
      </a>
    </div>
    <el-form :model="loginForm"
             :rules="loginRules"
             :style="toTop"
             class="login-content"
             label-position="left"
             label-width="0px"
             ref="loginForm">
      <h3 class="title">登录你的账户</h3>
      <el-form-item prop="account">
        <el-input auto-complete="off" placeholder="账号" type="text" v-model="loginForm.account"></el-input>
      </el-form-item>
      <el-form-item prop="checkPass">
        <el-input auto-complete="off" placeholder="密码" type="password" v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-checkbox checked class="remember" v-model="checked">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" @click.native.prevent="handleLogin" style="width:100%;" type="primary">登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import winControl from '../../../main/windowControl.js'
  import { debounce } from '../../utils/index'
  import { authUrl, userUrl } from '../../api/apiUrl'
  import axios from 'axios'
  import '../../assets/element-theme-custom/index.css'

  export default {
    data() {
      const validateAccount = (rule, value, callback) => {
        if (value.length <= 0) {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      }
      const validatePass = (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error('密码不能小于5位'))
        } else {
          callback()
        }
      }
      return {
        loginForm: {
          account: 'gongym',
          password: 'GongymPassword@im.com'
        },
        loginRules: {
          account: [{ required: true, trigger: 'blur', validator: validateAccount }],
          password: [{ required: true, trigger: 'blur', validator: validatePass }]
        },
        loading: false,
        checked: true,
        toTop: {
          margin: '0px auto'
        }
      }
    },
    mounted() {
      this.adaptationHeight()
      this._resizeHanlder = debounce(() => {
        this.adaptationHeight()
      }, 300)
      window.addEventListener('resize', this._resizeHanlder)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this._resizeHanlder)
    },
    methods: {
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            const param = new URLSearchParams()
            param.append('username', this.loginForm.account)
            param.append('password', this.loginForm.password)
            param.append('grant_type', 'password')
            param.append('scope', 'all')
            const that = this
            axios({
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic aW1fc2VydmVyOmltX3NlcnZlcg=='
              },
              method: 'POST',
              url: authUrl,
              data: param
            }).then(response => {
              // noinspection ES6ShorthandObjectProperty
              let userInfo = {
                access_token: '',
                refresh_token: '',
                token_type: '',
                expires_in: ''
              }
              userInfo = response.data
              // 获取用户ID
              const authorizationToken = userInfo.token_type + ' ' + userInfo.access_token
              axios({
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': authorizationToken
                },
                method: 'POST',
                url: userUrl,
                data: param
              }).then(response => {
                // 如果登录成功，保存到lowdb中一条数据，更换用户时更新这条数据
                userInfo.userId = response.data.data
                userInfo.id = 'user'
                that.$db.read().set('user', userInfo).write()
                that.$router.push({ name: 'Chat' })
                that.loading = false
              })
            }).catch(function(error) {
              that.loading = false
              this.$message({
                message: error,
                type: 'error',
                duration: 5 * 1000
              })
            })
          } else {
            return false
          }
        })
      },
      close() {
        winControl.close()
      },
      adaptationHeight() {
        // noinspection JSUnresolvedVariable
        const height = window.innerHeight - this.$refs['loginForm'].$el.offsetHeight
        this.toTop.margin = height / 2 + 'px auto'
      }
    }
  }
</script>
